package cn.bigcontainer.alt.sys.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.bigcontainer.alt.common.exception.BigResultCode;
import cn.bigcontainer.alt.sys.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import cn.bigcontainer.alt.sys.config.SiteConfig;
import cn.bigcontainer.alt.sys.dto.MenuDto;
import cn.bigcontainer.alt.sys.dto.UserDto;
import cn.bigcontainer.alt.sys.service.MainService;
import cn.bigcontainer.alt.sys.util.SysConstant;
import cn.bigcontainer.alt.sys.util.SysUtil;

/**
 * @author jiaod
 */
@Controller
@SessionAttributes(SysConstant.SESSION_USER)
public class MainController {

    private final static Logger LOG = LoggerFactory.getLogger(MainController.class);

    @Resource // @Autowired
    private MainService mainService;

    @Resource // @Autowired
    private SiteConfig siteConfig;
    
    /**
     * @param menu
     * @param map
     * @return
     */
    @RequestMapping("/management")
    public String toMain(String menu, Map<String, Object> map, @RequestParam Map<String, Object> req) {
        // 获取session中的用户
        UserDto u = SysUtil.getCurrentUser(map);
        // 如果session中没有用户数据，则重定向到登录页
        if (u == null) {
            return "redirect:/login";
        }
        // 获取顶级菜单，需要根据menu值来设置active（设置选中菜单）
        List<MenuDto> tops = u.getTops(menu);
        // map.put("tops", tops);
        String url = null;
        // 获取选中二级菜单的url
        for (MenuDto t : tops) {
            if (t.getActive()) {
                for (MenuDto c : t.getChildren()) {
                    if (c.getActive()) {
                        url = c.getUrl2(req);
                    }
                }
            }
            // 对所有类型为通知的菜单设置request
            if (t.getType().equals(MenuDto.TYPE_NOTIFICATION)) {
            	for (MenuDto c : t.getChildren()) {
                    if (c.getApp() == null) {
                    	continue;
                    }
                    c.getApp().getObject().getRequest().putAll(req);
                }
            }
        }
        if (url != null) {
            map.put("url", url);
        }
        return "main";
    }

    /**
     * 加载登录页
     *
     * @return
     */
    @GetMapping("/login")
    public String login(String error, Map<String, Object> map) {
        map.put("error", error);
        // 视图名称
        return siteConfig.getLogin();
    }

    /**
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password, Map<String, Object> map) {
        try {
            UserDto u = this.mainService.authenticate(username, password);
            map.put(SysConstant.SESSION_USER, u);
            return "redirect:" + siteConfig.getHome();
        } catch (Exception e) {
            LOG.error("", e);
            map.put("error", e.getMessage());
            return siteConfig.getLogin();
        }
    }

    @RequestMapping("/logout")
    public String logout (Map<String, Object>map, SessionStatus sessionStatus) {
        map.remove(SysConstant.SESSION_USER);
        sessionStatus.setComplete();
        return "redirect:/login";
    }

    @PostMapping("/password")
    @ResponseBody
    public BigResultCode setPassword (String oldPassword, String newPassword, String newPassword2, Map<String,Object> map) {
        mainService.modifyPassword (oldPassword, newPassword, newPassword2, SysUtil.getCurrentUserWithException(map));
        return BigResultCode.getSuccessCode();
    }

    @Resource // @Autowired
    private SysUserService userService;

    @PostMapping("/password/reset")
    @ResponseBody
    public BigResultCode resetPassword (String selectedIds, Map<String,Object> map) {
        SysUtil.getCurrentUserWithException(map);
        userService.resetPasswordByUserId(selectedIds);
        return BigResultCode.getSuccessCode();
    }
}
